package com.jule.miaozhuapc.service.impl;

import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jule.miaozhuapc.dao.GameRecordDao;
import com.jule.miaozhuapc.dao.PayDao;
import com.jule.miaozhuapc.dao.RoomDao;
import com.jule.miaozhuapc.dao.UserDao;
import com.jule.miaozhuapc.domain.WawaGameRecord;
import com.jule.miaozhuapc.domain.WawaPay;
import com.jule.miaozhuapc.domain.WawaRoom;
import com.jule.miaozhuapc.domain.WawaUser;
import com.jule.miaozhuapc.service.GameService;
import com.jule.miaozhuapc.util.Const;
import com.jule.miaozhuapc.webSocket.control.GameUserBean;


@Service
@Transactional
public class GameServiceImpl implements GameService{

	@Autowired
	UserDao userDao;
	@Autowired
	RoomDao roomDao;
	@Autowired
	GameRecordDao gameRecordDao;
	@Autowired
	PayDao payDao;
	
	@Override
	public GameUserBean StartGame(Long userId, Long roomId) {
		GameUserBean gameUser = new GameUserBean();
		gameUser.setIsPay(false);

		//查下该用户
		WawaUser user = userDao.findByUserId(userId);
		WawaRoom room = roomDao.findById(roomId);
		if (user != null && room != null && user.getCoin() >= room.getCoin()) {
			WawaGameRecord wawaGameRecord = new WawaGameRecord();
			wawaGameRecord.setAddTime(new Date());
			wawaGameRecord.setIsSuccess(false);
			wawaGameRecord.setUserId(userId);
			wawaGameRecord.setRoomId(roomId);
			wawaGameRecord.setWawaId(room.getWawaId());
			wawaGameRecord.setCoin(room.getCoin());
			gameRecordDao.update(wawaGameRecord);
			
			// 游戏记录
			WawaPay wawaPay = new WawaPay();
			wawaPay.setAddTime(new Date());
			wawaPay.setCoin(-room.getCoin());
			wawaPay.setMoney(0);
			wawaPay.setGameRecordId(wawaGameRecord.getId());
			wawaPay.setType( Const.WAWA_PAY_TYPE_GAME_RECORD);
			//FIXME
			wawaGameRecord.setCoverPage("开始游戏");
			wawaPay.setUserId(userId);
			payDao.insertPay(wawaPay);

			//用户剩余金币减
			user.setCoin(user.getCoin() - room.getCoin());

			//返回对象
			gameUser.setGameId(wawaGameRecord.getId());
			gameUser.setGameTime(room.getGameTime());
			gameUser.setUserId(userId);
			gameUser.setWxNickName(user.getWxNickName());
			gameUser.setIsPay(true);
			gameUser.setWxPic(user.getWxPic());
			gameUser.setCoin(user.getCoin());
			//FIXME
			gameUser.setWawaName("娃娃");
		}
		return gameUser;
	}

	@Override
	public void GameOver(GameUserBean gameUser, boolean rst) {
		// TODO Auto-generated method stub
		WawaGameRecord gameRecord = gameRecordDao.findById(gameUser.getGameId());
		gameRecord.setIsSuccess(rst);
		//FIXME
		gameRecord.setVideo("游戏结束");
		
		WawaUser user = userDao.findByUserId(gameUser.getUserId());
		if (rst ) {
			user.setSucCount( user.getSucCount()+1);
		}
	}
}
